const app = getApp()

const callCloud = options => {
  if (app && typeof app.callCloudFunction === "function") {
    return app.callCloudFunction(options);
  }
  const { loadingTitle, ...rest } = options;
  const title =
    typeof loadingTitle === "string" && loadingTitle.trim()
      ? loadingTitle.trim()
      : "加载中...";
  wx.showLoading({ title, mask: true });
  const originalComplete = rest.complete;
  rest.complete = (...args) => {
    if (typeof originalComplete === "function") {
      originalComplete(...args);
    }
  };
  return wx.cloud.callFunction(rest);
}

const truncateToastMessage = (message, maxLength = 18) => {
  const source = typeof message === "string" ? message : String(message || "");
  const chars = Array.from(source);
  if (chars.length <= maxLength) {
    return source;
  }
  return `${chars.slice(0, maxLength).join("")}...`;
};

Page({
  data: {
    isEditing: false,
    Nickname: "",
    Avatar: "", // 默认微信头像
    showChoose: false,
    Name: "",
    GenderIndex: 0,
    GenderText: "",
    StudentID: "",
    StudentTypeIndex: 0,
    StudentTypeText: "",
    EnrollmentYear: "",
    EnrollmentYearIndex: 0,
    College: "",
    Major: "",
    PhoneNumber: "",
    yearRange: []
  },

  onLoad() {
    this.initYearRange()
    this.waitUserInfo()
  },

  // 初始化年份倒序
  initYearRange() {
    const currentYear = new Date().getFullYear()
    const years = []
    for(let y=currentYear; y>=1950; y--){
      years.push(y)
    }
    this.setData({ yearRange: years })
  },

  waitUserInfo() {
    if (app.globalData.userInfo) {
      this.initUser(app.globalData.userInfo)
    } else {
      const timer = setInterval(()=>{
        if(app.globalData.userInfo){
          clearInterval(timer)
          this.initUser(app.globalData.userInfo)
        }
      },200)
    }
  },

  initUser(user){
    const hasGender = user.gender === 1 || user.gender === 2
    const genderIndex = hasGender ? (user.gender === 1 ? 0 : 1) : 0
    const genderText = hasGender ? (user.gender === 1 ? "男" : "女") : ""

    const studentTypeMap = ["本科","硕士","博士"]
    const hasStudentType = [1,2,3].includes(user.studentType)
    const studentTypeIndex = hasStudentType ? user.studentType - 1 : 0
    const studentTypeText = hasStudentType ? studentTypeMap[studentTypeIndex] : ""

    let enrollmentYear = user.enrollmentYear || ""
    if (enrollmentYear && typeof enrollmentYear !== "number") {
      const parsedYear = Number(enrollmentYear)
      if (!Number.isNaN(parsedYear)) {
        enrollmentYear = parsedYear
      } else {
        const parsedDate = new Date(enrollmentYear)
        if (!Number.isNaN(parsedDate.getFullYear())) {
          enrollmentYear = parsedDate.getFullYear()
        }
      }
    }
    const yearIndex = this.data.yearRange.indexOf(enrollmentYear)

    const hasEnrollmentYear = enrollmentYear !== "" && enrollmentYear !== null && enrollmentYear !== undefined
    const isProfileIncomplete = !hasGender || !hasStudentType || !hasEnrollmentYear || !user.studentID
    const shouldForceEdit = !!user.isUnregistered || isProfileIncomplete
    const nextIsEditing = shouldForceEdit ? true : this.data.isEditing

    this.setData({
      Nickname: user.nickname || "",
      Avatar: user.avatar || "",
      Name: user.name || "",
      GenderIndex: genderIndex,
      GenderText: genderText,
      StudentID: user.studentID || "",
      StudentTypeIndex: studentTypeIndex,
      StudentTypeText: studentTypeText,
      EnrollmentYear: enrollmentYear || "",
      EnrollmentYearIndex: yearIndex >= 0 ? yearIndex : 0,
      College: user.college || "",
      Major: user.major || "",
      PhoneNumber: user.phoneNumber || "",
      isEditing: nextIsEditing
    })
  },

  onEditTap() { this.setData({ isEditing:true }) },
  onCancelTap() { 
    this.setData({ isEditing:false }) 
    this.waitUserInfo()
  },

  onInputChange(e){
    const field = e.currentTarget.dataset.field
    this.setData({ [field]: e.detail.value })
  },
  // 从相册/相机选择头像，保持原有上传流程（微信头像面板已包含此能力，保留方法以兼容旧发版）
  chooseLocalAvatar(){
    if(!this.data.isEditing) return
    wx.chooseImage({
      count:1,
      sizeType:['original','compressed'],
      sourceType:['album','camera'],
      success: res=>{
        const tempFilePath = res.tempFilePaths[0]
        this.uploadAvatar(tempFilePath, '头像已更新')
      }
    })
  },

  // 处理 open-type="chooseAvatar" 回调，兼容微信头像与本地图片
  onChooseWechatAvatar(e){
    if(!this.data.isEditing) return
    const avatarUrl = e.detail?.avatarUrl
    if(!avatarUrl){
      wx.showToast({ title:'未获取到头像', icon:'none'})
      return
    }
    if(/^https?:\/\//.test(avatarUrl)){
      wx.showLoading({ title:'上传中...' })
      wx.downloadFile({
        url: avatarUrl.replace(/\/132$/, '/0'),
        success: downloadRes=>{
          if(downloadRes.statusCode === 200 && downloadRes.tempFilePath){
            this.uploadAvatar(downloadRes.tempFilePath, '已完成')
          } else {
            wx.showToast({ title:'头像获取失败', icon:'none'})
          }
        },
        fail: ()=>{
          wx.showToast({ title:'头像获取失败', icon:'none'})
        }
      })
    } else {
      this.uploadAvatar(avatarUrl, '已完成')
    }
  },

  // 统一的头像上传逻辑，上传至云存储后更新界面
  uploadAvatar(tempFilePath, toastTitle){
    if(!tempFilePath) return
    wx.showLoading({ title:'上传中...' })
    const random = Math.floor(Math.random()*1000)
    const cloudPath = `avatars/${Date.now()}-${random}.png`
    wx.cloud.uploadFile({
      cloudPath,
      filePath: tempFilePath,
      success: uploadRes=>{
        this.setData({ Avatar: uploadRes.fileID })
        wx.showToast({ title: toastTitle || '头像已更新', icon:'success'})
      },
      fail: ()=>{
        wx.showToast({ title:'上传失败', icon:'none'})
      }
    });
  },

  onGenderChange(e){
    const idx = Number(e.detail.value)
    this.setData({
      GenderIndex: idx,
      GenderText: idx==0?"男":"女"
    })
  },

  onStudentTypeChange(e){
    const idx = Number(e.detail.value)
    this.setData({
      StudentTypeIndex: idx,
      StudentTypeText: ["本科","硕士","博士"][idx]
    })
  },

  onEnrollmentYearChange(e){
    const idx = Number(e.detail.value)
    this.setData({
      EnrollmentYearIndex: idx,
      EnrollmentYear: this.data.yearRange[idx]
    })
  },

  onSaveTap(){
    // 必填字段中文提示
    const requiredFields = [
      {key:"Nickname", label:"昵称"},
      {key:"Name", label:"姓名"},
      {key:"StudentID", label:"学号"},
      {key:"GenderText", label:"性别"},
      {key:"StudentTypeText", label:"学生类型"},
      {key:"EnrollmentYear", label:"入学年份"},
      {key:"College", label:"学院"},
      {key:"Major", label:"专业"},
      {key:"PhoneNumber", label:"电话"}
    ]

    const missing = requiredFields.filter(f=>!this.data[f.key] || this.data[f.key].toString().trim()==="").map(f=>f.label)

    if(missing.length>0){
      const baseMessage = `以下信息不完整：${missing.join("、")}`
      const displayMessage = truncateToastMessage(baseMessage)
      wx.showToast({ title: displayMessage, icon:"none" })
      return
    }
    const enrollmentYearValue = this.data.EnrollmentYear ? new Date(this.data.EnrollmentYear,8,1).toISOString() : ""
    callCloud({
      name:"setUserInfo",
      loadingTitle: "保存中...",
      data:{
        nickname: this.data.Nickname,
        avatar: this.data.Avatar,
        name: this.data.Name,
        gender: this.data.GenderIndex==0?1:2, // 男=1 女=2
        studentID: this.data.StudentID,
        studentType: this.data.StudentTypeIndex+1,
        enrollmentYear: enrollmentYearValue,
        college: this.data.College,
        major: this.data.Major,
        phoneNumber: this.data.PhoneNumber
      },
      success: res=>{
        if(res.result.success){
          wx.showToast({title:"保存成功", icon:"success"})
          this.setData({ isEditing:false })
          // 更新全局 userInfo
          app.globalData.userInfo = {
            ...app.globalData.userInfo,
            nickname:this.data.Nickname,
            avatar:this.data.Avatar,
            name:this.data.Name,
            gender:this.data.GenderIndex==0?1:2,
            studentID:this.data.StudentID,
            studentType:this.data.StudentTypeIndex+1,
            enrollmentYear:enrollmentYearValue,
            college:this.data.College,
            major:this.data.Major,
            phoneNumber:this.data.PhoneNumber,
            isUnregistered:false
          }
          if (typeof app.updateUserProfileState === "function") {
            app.updateUserProfileState(app.globalData.userInfo);
          }
        } else {
          wx.showToast({title:res.result.error || "保存失败", icon:"none"})
        }
      },
      fail: err=>{
        wx.showToast({title:"保存出错", icon:"error"})
        console.error(err)
      }
    })
  }
})
